<?php
class CartEditForm extends Form
{
	private $cart = array(), $cart_items = array(), $items = array();
	
	function CartEditForm()
	{
		Form::Form('CartEditForm');
		
		CGlobal::$website_title = "Xem & Sửa đơn hàng";
		
		$this->link_js('javascript/aznet/cart.js');
		
		$id	=	URL::get('id',0);
		
		if($id)
		{
			$this->cart = DB::select("cart","id=$id");
			
			if($this->cart)
			{
				$re = DB::query("SELECT * FROM cart_item WHERE cart_id=".$this->cart['id']." ORDER BY id DESC");
				
				$cart_item_del 	= '';
				$item_ids 		= '';
				
				if($re)
				{
					while($cart_item = mysql_fetch_assoc($re))
					{
						$item_ids .= ($item_ids != '' ? ',' : '') . $cart_item['item_id'];
						
						$this->cart_items[$cart_item['id']]	= $cart_item;
					}
				}
			
				if($item_ids != '')
				{
					$re = DB::query("SELECT * FROM item WHERE id IN(".$item_ids.") AND status=1 AND price>0");
				
					if($re)
					{
						while($item = mysql_fetch_assoc($re))
						{
							$item['price'] = AZLib::convertCurrency($item['price'],$item['currency_id']);
							
							$this->items[$item['id']]	= $item;		
						}
					}
				}

				$cart_item_del = '';
				
				foreach ($this->cart_items as $cart_item)
				{
					if(isset($this->items[$cart_item['item_id']]))
					{
						if($cart_item['price'] != $this->items[$cart_item['item_id']]['price'] || $cart_item['sku'] != $this->items[$cart_item['item_id']]['sku'])
						{
							$cart_item['price'] = $this->items[$cart_item['item_id']]['price'];
							$cart_item['sku'] 	= $this->items[$cart_item['item_id']]['sku'];
							
							DB::update('cart_item',array('price'=>$cart_item['price'],'sku'=>$cart_item['sku']),"id={$cart_item['id']}");
						}
						
						$this->cart_items[$cart_item['id']]	= $cart_item;
					}
					else
					{
						$cart_item_del .= ($cart_item_del != '' ? ',' : '') . $cart_item['id'];
					}
				}
				
				if($cart_item_del != '')
				{
					DB::delete('cart_item',"id IN($cart_item_del)");
				}
			}
		}
		
		if(!$this->cart)
		{
			URL::redirect_current();
		}
		
		if(Url::get('act') == 'del_item')
		{
			$id	=	Url::get('ci_id',0);
	
			if($id && $this->cart && isset($this->cart_items[$id]))
			{
				DB::delete('cart_item',"id=$id AND cart_id=".$this->cart['id']);
				
				DB::update("cart",array("time_change"=>TIME_NOW),"id=".$this->cart['id']);
			}
	
			$cart_price 	= DB::fetch("SELECT SUM(price * quantity) AS price_total FROM cart_item WHERE cart_id=".$this->cart['id']." AND checked=1 AND price>0 ANd quantity>0",'price_total',0);
			$cart_quantity 	= DB::fetch("SELECT SUM(quantity) AS price_quantity FROM cart_item WHERE cart_id=".$this->cart['id']." AND checked=1 AND price>0 ANd quantity>0",'price_quantity',0);
			
			if($this->cart['price'] != $cart_price || $this->cart['quantity'] != $cart_quantity)
			{
				$this->cart['price'] 	= $cart_price;
				$this->cart['quantity'] = $cart_quantity;
				
				DB::update("cart",array('price'=>$cart_price,'quantity'=>$cart_quantity),'id='.$this->cart['id']);
			}
			
			Url::redirect_current(array('cmd','id'));
		}
	}
	
	function on_submit()
	{
		$status				=	URL::get('status');
		
		$customer_name		=	URL::get('customer_name');
		$customer_email		=	URL::get('customer_email');
		$customer_phone		=	URL::get('customer_phone');
		$customer_address	=	URL::get('customer_address');
		$customer_note		=	URL::get('customer_note');
		$note				=	URL::get('note');
		
		$this->checkFormInput("Tên đầy đủ",'customer_name',$customer_name,'str',true,'',2,50);
		$this->checkFormInput("Email",'customer_email',$customer_email,'email',true,'',false,50);
		$this->checkFormInput("Điện thoại liên hệ",'customer_phone',$customer_phone,'str',true,'',9,50);
		$this->checkFormInput("Địa chỉ",'customer_address',$customer_address,'str',true,'',false,500);
		$this->checkFormInput("Ghi chú",'customer_note',$customer_note,'str',false,'',false,500);
		
		if(!$this->errNum)
		{
			$arr	=	array(
							'customer_name'		=>addslashes($customer_name),
							'customer_email'	=>addslashes($customer_email),
							'customer_phone'	=>addslashes($customer_phone),
							'customer_address'	=>addslashes($customer_address),
							'customer_note'		=>addslashes($customer_note),
							'time_change'		=>TIME_NOW,
							'mm_user_id'		=>User::id(),
							'mm_user_name'		=>User::user_name(),
							'mm_time_modify'	=>TIME_NOW,
							'note'				=>addslashes($note),
							);
									
			if(DB::update('cart',$arr,"id=".$this->cart['id']))
			{
				//DB::update("cart_item",array('status'=>$status),"cart_id=".$this->cart['id']." AND checked=1");//0:Chưa TT; 1: Đã gửi đơn hàng; 2:Đã TT; 3: Hủy đơn hàng
				
				
				$quantitys	=	Url::get('quantity');
				$checkeds	=	Url::get('checked');
				
				$cart_price 	= 0;
				$cart_quantity 	= 0;
					
				if($quantitys)
				{
					$sql_arr=array();
					
					foreach ($quantitys as $id	=>	$quantity)
					{
						if($quantity < 1)
						{
							$quantity = 1;
						}
						
						$checked = (int)@$checkeds[$id];
						
						$sql_arr[]	=	"UPDATE cart_item SET quantity=".(int)$quantity.", checked=$checked, status=$status WHERE id=".$id;
						
						if($checked)
						{
							$cart_price 	+= $this->cart_items[$id]['price'] * $quantity;
							$cart_quantity	+= $quantity;
						}
					}
					
					if($sql_arr)
					{
						foreach ($sql_arr as $query)
						{
							DB::query($query);
						}
					}
				}
				
				if($this->cart['price'] != $cart_price || $this->cart['quantity'] != $cart_quantity)
				{
					DB::update("cart",array('price'=>$cart_price,'quantity'=>$cart_quantity),'id='.$this->cart['id']);
				}
				
				URL::redirect_current(array('cmd','id'));
			}
			else 
				$this->setFormError("customer_name","Không cập nhật được, mời bạn thử lại!");
		}
	}
	
	function draw()
	{
		global $display;
		
		$display->add('msg',$this->showFormErrorMessages(1));
		
		if($this->cart['user_id'])
		{
			$display->add("user_name", $this->cart['user_name']);
		}
		
		$display->add("user_id", $this->cart['user_id']);
		
		$display->add("customer_name",		stripslashes(URL::get('customer_name',$this->cart['customer_name'])));
		$display->add("customer_email",		stripslashes(URL::get('customer_email',$this->cart['customer_email'])));
		$display->add("customer_phone",		stripslashes(URL::get('customer_phone',$this->cart['customer_phone'])));
		$display->add("customer_address",	stripslashes(URL::get('customer_address',$this->cart['customer_address'])));
		$display->add("customer_note",		stripslashes(URL::get('customer_note',$this->cart['customer_note'])));
		$display->add("note",				stripslashes(URL::get('note',$this->cart['note'])));
				
		//$quantity_total	=0;
		$price_total	=0;
			
		$cart_items = array();
		
		if($this->cart_items)
		{
			foreach ($this->cart_items  as $cart_item_id => $cart_item)
			{
				$item = $this->items[$cart_item['item_id']];
				
				if(isset(CGlobal::$allCategories[$item['category_id']]))
				{
					$cart_item['url'] = WEB_DIR.CGlobal::$allCategories[$item['category_id']]['nice_name']."/p{$item['id']}/".AZLib::safe_title($item['name']).".html";
				}
				else{	
					$cart_item['url'] = WEB_DIR."p{$item['id']}/".AZLib::safe_title($item['name']).".html";
				}
		
				$cart_item['name'] 		= $item['name'];
				$cart_item['price_num'] = $item['price'];
				
				$cart_item['price'] 	= number_format($item['price'],0,',','.');
				
				if ($item['img_url']){
					$cart_item['img_url'] 		= AZLib::getImageThumb($item['img_url'],120,120,0,$item['img_server']);
				}
				else{
					$item['img_url'] 			=  '';
				}
				
				
				$cart_item["delete"] 		= Url::build_current(array('cmd','id','act'=>'del_item','ci_id'=>$cart_item['id']));
				
				
				
				$cart_item['row_total'] = $cart_item['checked'] ? (number_format($item['price'] * $cart_item['quantity'],null,null,'.')) . ' VNĐ' : '';
				
				$price_total	+=	$cart_item['checked'] ? ($item['price'] * $cart_item['quantity']) : 0;
				//$quantity_total	+=	$cart_item['checked'] ? $cart_item['quantity'] : 0;
				
				$cart_items[$cart_item['id']] = $cart_item;
			}
		}
			
		$display->add('price_total', number_format($price_total,null,null,'.'));
		
		$display->add('url_finish',Url::build_current(array('cmd'=>'finish')));
		$display->add('cart_items',$cart_items);
		
		//1:Chưa cập nhật; 2: Đã gửi đơn hàng ; 3: Đã TT; 4: Hủy đơn hàng; 5: Đã duyệt
		$status_arr	=	array(
								6	=>	"--Tất cả--",
								2	=>	"Đã gửi đơn hàng",
								1	=>	"Chưa cập nhật",
								3	=>	"Đã Thanh toán",
								5	=>	"Đã duyệt",
								4	=>	"Đã hủy"
								);
		
		$display->add("status_option",AZLib::getOption($status_arr,$this->cart['status']));
		
		$display->add('cart_id',"Cart_".$this->cart['id']);
		
		$display->add("time_create",date('d/m/Y H:i:s',$this->cart['time_create']));
		$display->add("time_change",date('d/m/Y H:i:s',$this->cart['time_change']));
		
		if($this->cart['time_finish'])
			$display->add("time_finish",date('d/m/Y H:i:s',$this->cart['time_finish']));
		else
			$display->add("time_finish","Chưa hoàn thành!");
		
		
		
		$this->beginForm();
		$display->output('CartEdit');
		$this->endForm();
	}
}
?>